package com.duobaoyu.dby.supply.biz.interceptor;

import com.duobaoyu.dby.supply.biz.annotation.TableQueryHead;
import com.duobaoyu.dby.supply.db.helper.DynamicTableNameHelper;
import com.google.common.collect.Maps;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @author yw
 * @description 表查询属性设置拦截器
 * @date 2023/9/28 10:18
 */
@Slf4j
@NoArgsConstructor
public class TableQueryHeadInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			TableQueryHead tableQueryHead = null;
			if (handlerMethod.hasMethodAnnotation(TableQueryHead.class)) {
				tableQueryHead = handlerMethod.getMethodAnnotation(TableQueryHead.class);
			} else if (handlerMethod.getBeanType().isAnnotationPresent(TableQueryHead.class)) {
				tableQueryHead = handlerMethod.getBeanType().getAnnotation(TableQueryHead.class);
			}
			if (Objects.nonNull(tableQueryHead)) {
				String tableName = tableQueryHead.tableName();
				String value = request.getHeader(tableQueryHead.key());
				Map<String, Object> requestData = Maps.newHashMap();
				requestData.put(tableName, StringUtils.isBlank(value) ? tableQueryHead.value() : value);
				DynamicTableNameHelper.setRequestData(requestData);
			}
		}
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		DynamicTableNameHelper.removeRequestData();
	}
}
